//
//  MBChatListViewController.m
//  Meboo
//
//  Created by kyo on 2023/10/16.
//

#import "MBChatListViewController.h"
#import "MBConversationViewController.h"
#import "MBChatDataManager.h"
#import "MBChatListViewController.h"
#import "MBChatListCell.h"
#import "MBChatNavView.h"
#import <UIScrollView+EmptyDataSet.h>

@interface MBChatListViewController ()
<
UITableViewDelegate,
UITableViewDataSource,
DZNEmptyDataSetSource,
DZNEmptyDataSetDelegate
>
@property (nonatomic, strong) UIImageView *backImageView;
//
@property (nonatomic, strong) MBChatNavView *chatNavView;
//kefu
@property (nonatomic, strong) RCUserInfo *kefuInfo;
//
@property (nonatomic, assign) BOOL isUpdate;
//
@property (nonatomic, strong) MBChatDataManager *chatDataManager;

//定时刷新在线状态
@property (nonatomic ,strong) NSTimer *onlineTimer;
//所有id的数组
@property (nonatomic ,strong) NSMutableArray *codeArr;
@end

@implementation MBChatListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.emptyConversationView.alpha = 0;
    [self setupUI];
    [self getKefuInfo];
    self.conversationListTableView.emptyDataSetSource = self;
    self.conversationListTableView.emptyDataSetDelegate = self;
    [self onlineTimer];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (!self.isUpdate) {
        [self getRCUserInfo];
    }
    [self reloadOnline];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.onlineTimer invalidate];
}

//#pragma mark - 设置状态栏颜色
//- (UIStatusBarStyle)preferredStatusBarStyle {
//    return UIStatusBarStyleLightContent;
//}

#pragma mark -- 定时刷新在线状态
- (void)reloadOnline {
    if (self.codeArr.count == 0) {
        [self getCodeArrAfterLoad];
    }
    __WeakSelf
    [self.chatDataManager getUserOnlineWithUserCodes:self.codeArr success:^(BOOL success) {
        if (success && self.chatDataManager.onlineCodeArr.count > 0) {
            
            if (weakSelf.conversationListDataSource.count > 0) {
                for (RCConversationModel *conModel in weakSelf.conversationListDataSource) {
                    if ([self.chatDataManager.onlineCodeArr containsObject:conModel.targetId]) {
                        conModel.extend = @"1";
                    } else {
                        conModel.extend = @"0";
                    }
                }
                [weakSelf.conversationListTableView reloadData];
            }
        }
    }];
}

- (void)getCodeArrAfterLoad {
    [self.codeArr removeAllObjects];
    for (MBChatNewFriendsModel *model in self.chatDataManager.newFriendsDataArr) {
        [self.codeArr addObject:model.userCode];
    }
    for (RCConversationModel *model in self.conversationListDataSource) {
        [self.codeArr addObject:model.targetId];
    }
}

#pragma mark - Private Method
- (void)getRCUserInfo {
    __WeakSelf
    dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t group = dispatch_group_create();
    
    for (RCConversationModel *model in self.conversationListDataSource) {
        RCUserInfo *userInfo = [[RCIM sharedRCIM] getUserInfoCache:model.targetId];
        if (userInfo.portraitUri.length == 0) {
            weakSelf.isUpdate = YES;
            dispatch_group_enter(group);
            dispatch_group_async(group, queue, ^{
                [weakSelf.chatDataManager getUserInfoWithUserId:model.targetId completion:^(RCUserInfo * _Nonnull userInfo) {
                    [[RCIM sharedRCIM] refreshUserInfoCache:userInfo withUserId:model.targetId];
                    dispatch_group_leave(group);
                }];
            });
        }
    }
    
    dispatch_group_notify(group, queue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (weakSelf.isUpdate) {
                [weakSelf.conversationListTableView reloadData];
            }
        });
    });
    
    //自己的信息也加载一遍  无需进组,因为不参与本页面刷新 在下个页面会用到
    RCUserInfo *meInfo = [[RCIM sharedRCIM] getUserInfoCache:[MBUserAccount defaultAccount].chatUserId];
    if (meInfo.portraitUri.length == 0) {
        [weakSelf.chatDataManager getUserInfoWithUserId:[MBUserAccount defaultAccount].chatUserId completion:^(RCUserInfo * _Nonnull userInfo) {
            [[RCIM sharedRCIM] refreshUserInfoCache:userInfo withUserId:[MBUserAccount defaultAccount].chatUserId];
        }];
    }
}

- (void)getKefuInfo {
    if ([MBUserAccount defaultAccount].kefuTargetId.length > 0) {
        self.kefuInfo = [[RCIM sharedRCIM] getUserInfoCache:[MBUserAccount defaultAccount].kefuTargetId];
        return;
    }
    __WeakSelf
    [self.chatDataManager getChatKefuUrl:^(RCUserInfo * _Nonnull userInfo) {
        if (userInfo) {
            weakSelf.kefuInfo = userInfo;
            [[RCIM sharedRCIM] refreshUserInfoCache:userInfo withUserId:userInfo.userId];
            MBUserAccount  *account = [MBUserAccount defaultAccount];
            account.kefuTargetId = userInfo.userId;
            [MBUserAccount saveAccount:account];
            
            NSMutableArray *arr = [NSMutableArray arrayWithArray:self.conversationListDataSource];
            for (RCConversationModel *model in arr) {
                if ([model.targetId isEqualToString:userInfo.userId]) {
                    [self.conversationListDataSource removeObject:model];
                }
            }
            [weakSelf.conversationListTableView reloadData];
        }
    }];
}

- (void)onSelectedTableRow:(RCConversationModelType)conversationModelType
         conversationModel:(RCConversationModel *)model
               atIndexPath:(NSIndexPath *)indexPath {
__WeakSelf
    MBConversationViewController *conversationVC = [[MBConversationViewController alloc] initWithConversationType:ConversationType_PRIVATE targetId:model.targetId];
    conversationVC.isFromList = YES;
    conversationVC.sendMessageBlock = ^(NSInteger sendedNum) {
        [weakSelf.chatDataManager getUserMessageNumWithUserCode:model.targetId type:2 success:^(BOOL success) {
        }];
    };
//    RCConversationViewController *conversationVC = [[RCConversationViewController alloc] initWithConversationType:ConversationType_PRIVATE targetId:model.targetId];
    
    
    [self.navigationController pushViewController:conversationVC animated:YES];
}

- (void)showAddCartAnmationSview:(UIView *)sview
                       imageView:(UIView *)imageView
                        starPoin:(CGPoint)startPoint
                        endPoint:(CGPoint)endpoint
                     dismissTime:(float)dismissTime
{
    __block CALayer *layer;
    layer                               = [[CALayer alloc]init];
    layer.contents                      = imageView.layer.contents;
    layer.frame                         = imageView.frame;
    layer.opacity                       = 1;
    [sview.layer addSublayer:layer];
    UIBezierPath *path                  = [UIBezierPath bezierPath];
    [path moveToPoint:startPoint];
    //贝塞尔曲线控制点
    float sx                            = startPoint.x;
    float sy                            = startPoint.y;
    float ex                            = endpoint.x;
    float ey                            = endpoint.y;
    float x                             = sx + (ex - sx) / 3;
    float y                             = sy + (ey - sy) * 0.5;
    CGPoint centerPoint                 = CGPointMake(x, y);
    [path addQuadCurveToPoint:endpoint controlPoint:startPoint];
    //设置位置动画
    CAKeyframeAnimation *animation=[CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path                      = path.CGPath;
    animation.removedOnCompletion       = NO;
    //设置大小动画
    CGSize finalSize                    = CGSizeMake(imageView.bounds.size.height, imageView.bounds.size.width);
    CABasicAnimation *resizeAnimation   = [CABasicAnimation animationWithKeyPath:@"bounds.size"];
    resizeAnimation.removedOnCompletion = NO;
    [resizeAnimation setToValue:[NSValue valueWithCGSize:finalSize]];
    //旋转
    CABasicAnimation* rotationAnimation;
    rotationAnimation                   = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue           = [NSNumber numberWithFloat: M_PI * 2.0 ];
    rotationAnimation.cumulative        = YES;
    rotationAnimation.duration          = 300000;
    rotationAnimation.repeatCount       = 1000;
    //动画组
    CAAnimationGroup * animationGroup   = [[CAAnimationGroup alloc] init];
//    animationGroup.animations           = @[animation,resizeAnimation,rotationAnimation];
    animationGroup.animations           = @[animation];
    animationGroup.delegate             = self;
    animationGroup.duration             = dismissTime;
    animationGroup.removedOnCompletion  = NO;
    animationGroup.fillMode             = kCAFillModeForwards;
    animationGroup.autoreverses         = NO;
    animationGroup.timingFunction       = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    [layer addAnimation:animationGroup forKey:@"buy"];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(dismissTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [layer removeFromSuperlayer];
        layer = nil;
    });
}

//view转图片
- (UIImageView*)convertViewToImage:(UIView*)view {
    CGSize s = view.bounds.size;
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    
    UIImageView *imageView = [UIImageView new];
    imageView.frame = view.frame;
    imageView.image = image;
    return imageView;
}

#pragma mark -- tableView  delegate datasource
- (NSMutableArray *)willReloadTableData:(NSMutableArray *)dataSource {
    NSMutableArray * dataArr = [NSMutableArray array];
    for (RCConversationModel *model in dataSource) {
        model.conversationModelType = RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION;
        if (![model.targetId isEqualToString:[MBUserAccount defaultAccount].kefuTargetId]) {
            if ([self.chatDataManager.onlineCodeArr containsObject:model.targetId]) {
                model.extend = @"1";
            } else {
                model.extend = @"0";
            }
            [dataArr addObject:model];
        }
    }
    return dataArr;
}

- (RCConversationBaseCell *)rcConversationListTableView:(UITableView *)tableView
                                  cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MBChatListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MBChatListCell"];
    if (!cell) {
        cell = [[MBChatListCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MBChatListCell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    RCConversationModel *model = self.conversationListDataSource[indexPath.row];
    cell.model = model;
    cell.layer.cornerRadius = MBHeightScale(10);
    cell.clipsToBounds = YES;
    return cell;
}

//// 自定义 cell
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    
//    MBChatListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MBChatListCell"];
//    if (!cell) {
//        cell = [[MBChatListCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MBChatListCell"];
//    }
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    cell.model = self.dataArr[indexPath.row];
////    __WeakSelf
////    cell.rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"chat_conversion_delete"] backgroundColor:HEXS(@"FF4545") callback:^BOOL(MGSwipeTableCell * _Nonnull cell) {
////        // 删除按钮
////        CGFloat height = ScreenHeight -(ScreenHeight - MBHeightScale(192)-StatusBarAndNavigationBarHeight)/2;
////
////        CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];//获取cell在tableView中的位置
////        CGRect rectInSuperview = [tableView convertRect:rectInTableView toView:[tableView superview]];
////        cell.frame = rectInSuperview;
////        
////        UIView *view = weakSelf.view;
////        UIImageView *imageView = [weakSelf convertViewToImage:cell];
////        CGPoint startPoint = CGPointMake(ScreenWidth/2, cell.frame.origin.y+cell.frame.size.height/2);
////        
////        
////        CGPoint endPoint = CGPointMake(-MBHeightScale(225), height);
////        
////        
////        // 删除按钮
////        [weakSelf showAddCartAnmationSview:view imageView:imageView starPoin:startPoint endPoint:endPoint dismissTime:0.5];
////        [self.dataArr removeObjectAtIndex:indexPath.row];
////        [self.conversationListTableView reloadData];
////        return YES;
////    }]];
////    cell.rightSwipeSettings.transition = MGSwipeTransitionDrag;
//    cell.layer.cornerRadius = MBHeightScale(10);
//    cell.clipsToBounds = YES;
//    return cell;
//}


// 高度
- (CGFloat)rcConversationListTableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return MBHeightScale(76);
}

//左滑删除回调
- (void)rcConversationListTableView:(UITableView *)tableView
                 commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
                  forRowAtIndexPath:(NSIndexPath *)indexPath {
    __WeakSelf
        RCConversationModel *model = self.conversationListDataSource[indexPath.row];
    [[RCCoreClient sharedCoreClient] removeConversation:model.conversationType targetId:model.targetId completion:^(BOOL ret) {
        if (ret) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.conversationListDataSource removeObjectAtIndex:indexPath.row];
                [weakSelf.conversationListTableView reloadData];
            });
        }
    }];
    
    CGFloat height = ScreenHeight -(ScreenHeight - MBHeightScale(192)-StatusBarAndNavigationBarHeight)/2;
    MBChatListCell *cell = [self.conversationListTableView cellForRowAtIndexPath:indexPath];
    CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];//获取cell在tableView中的位置
    CGRect rectInSuperview = [tableView convertRect:rectInTableView toView:[tableView superview]];
    cell.frame = rectInSuperview;
    
    UIView *view = weakSelf.view;
    UIImageView *imageView = [weakSelf convertViewToImage:cell];
    CGPoint startPoint = CGPointMake(ScreenWidth/2, cell.frame.origin.y+cell.frame.size.height/2);
    
    
    CGPoint endPoint = CGPointMake(-225, height);
    
    
    [weakSelf showAddCartAnmationSview:view imageView:imageView starPoin:startPoint endPoint:endPoint dismissTime:0.5];
//    [self.dataArr removeObjectAtIndex:indexPath.row];
//    [self.conversationListTableView reloadData];
}


- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"chat_list_nodata"];
}

- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = @"Tap on a new match above to send a message";
    NSMutableDictionary *attribult = [NSMutableDictionary new];
    [attribult setObject:PDRegularScale(16) forKey:NSFontAttributeName];
    [attribult setObject:HEXS(@"666666") forKey:NSForegroundColorAttributeName];
    return [[NSAttributedString alloc] initWithString:text attributes:attribult];
}

#pragma mark - UI
- (void)setupUI {
    [self.view addSubview:self.backImageView];
    [self.view sendSubviewToBack:self.backImageView];
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.view addSubview:self.chatNavView];
    [self.chatNavView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(StatusBarAndNavigationBarHeight);
    }];
    
    self.conversationListTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.conversationListTableView.showsVerticalScrollIndicator = NO;
    self.conversationListTableView.backgroundColor = UIColor.clearColor;
//    self.conversationListTableView.frame = CGRectMake(MBHeightScale(20), MBHeightScale(192)+StatusBarAndNavigationBarHeight, ScreenWidth-MBHeightScale(40), ScreenHeight-StatusBarAndNavigationBarHeight-MBHeightScale(192));
    
    [self.conversationListTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.view);
        make.top.equalTo(self.chatNavView.mas_bottom).offset(MBHeightScale(10));
    }];
}

#pragma mark - Setter && Getter
- (MBChatDataManager *)chatDataManager {
    if (!_chatDataManager) {
        _chatDataManager = [[MBChatDataManager alloc] init];
    }
    return _chatDataManager;
}

- (MBChatNavView *)chatNavView {
    if (!_chatNavView) {
        _chatNavView = [MBChatNavView new];
    }
    return _chatNavView;
}

- (NSTimer *)onlineTimer {
    if (!_onlineTimer) {
        _onlineTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(reloadOnline) userInfo:nil repeats:YES];
    }
    return _onlineTimer;
}

- (NSMutableArray *)codeArr {
    if (!_codeArr) {
        _codeArr = [NSMutableArray array];
    }
    return _codeArr;
}

- (UIImageView *)backImageView {
    if (!_backImageView) {
        _backImageView = [UIImageView new];
        _backImageView.image = ImageWithName(@"home_back_image");
    }
    return _backImageView;
}
@end
